package wj;

import java.util.HashMap;

public class Scope {
	
	private Scope parent;
	private HashMap<String, WJValue> variables;	
	public static final Scope GLOBAL_SCOPE = new Scope(null);
	
	public Scope(Scope parent){
		this.parent = parent;
		variables = new HashMap<String, WJValue>();
	}
	
	public WJValue retrieveVarValue(String varName){
		if(variables.get(varName) != null)
			return variables.get(varName);
		
		if(parent == null)
			return WJValue.NULL;
		
		return parent.retrieveVarValue(varName);
	}
	
	public void assign(String varName, WJValue value){
		if(retrieveVarValue(varName).equals(WJValue.NULL)) //it doesn't exist yet
			variables.put(varName, value);
		else 
			reassign(varName, value);
	}
	
	public void reassign(String varName, WJValue value){
		if(variables.get(varName) != null) //it exists in this scope
			variables.put(varName, value);
		else if(parent != null) //pass on to parent because the variable does not exist in this scope
			parent.assign(varName, value); 
	}
	
}
